// TODO: CODE REVIEW & CLEANUP!
//
using System;
using System.Windows;
using HomeUX.ClientAppSupport;
using HomeUX.ClientControlSupport;
using HomeUX.Utilities;

namespace HomeUX.ClientApp
{

public partial class App : Application
{
    public StartupEventArgs StartupEventArgs { get; private set; }

    /// <summary>
    /// Gets the single application-wide instance of the <r>App</r> class.
    /// </summary>
    public static new App Current
    {
        get
        {
            return (App)Application.Current;
        }
    }

	public App() 
	{
		this.Startup += this.OnStartup;
		this.Exit += this.OnExit;
		this.UnhandledException += this.Application_UnhandledException;

		InitializeComponent();
	}

	private void OnStartup(object sender, StartupEventArgs e) 
	{
        // save <e>
        StartupEventArgs = e;

        // initialize ClientGlobals.SyncClientProvider
        ClientFramework.InitializeSyncClientProvider();

		// load the root-level control
		this.RootVisual = new Page();
    }

	private void OnExit(object sender, EventArgs e) 
	{
        Util.Trace("--- EXITING ---");

        // shut down the application framework
        if (ClientFramework.HasInstance)
            ClientFramework.Current.OnExit();
  
        Util.Trace("--- EXITED ---");
    }

	internal void Application_UnhandledException(object sender,
		ApplicationUnhandledExceptionEventArgs e)
	{
        // note: if a debugger is attached, it will have already caught and displayed the
        // exception -- this method is called if the user presses F5 to continue after the
        // exception
        e.Handled = true;
        if (!ClientGlobals.Alert(AlertType.Warning, "Unhandled exception: {0}",
            e.ExceptionObject))
        {
			try
			{
				string errorMsg = e.ExceptionObject.Message + @"\n" + e.ExceptionObject.StackTrace;
				errorMsg = errorMsg.Replace("\"", "\\\"").Replace("\r\n", @"\n");

#if false // let's see if the "weird mouse-related crash" has been fixed in Silverlight 3
				// ignore weird mouse-related crash
				if (errorMsg.Contains("MS.Internal.XcpImports.MouseEventArgs_GetPosition"))
				{
					//System.Windows.Browser.HtmlPage.Window.Eval("alert('bug happened')");
					return;
				}
#endif

				System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application: " + errorMsg + "\");");
			}
			catch (Exception)
			{
			}
		}
	}
}

}

